package com.eascs.workflow.sys.controller;

import com.eascs.app.dao.PageResult;
import com.eascs.app.exception.ControllerException;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.doc.excel.ExcelApiHelper;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.IoUtil;
import com.eascs.common.util.StringUtil;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.tag.MenuTag;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.controller.BaseMasterViewController;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.sys.dao.SysOrgDao;
import com.eascs.workflow.sys.dao.SysUserDao;
import com.eascs.workflow.sys.service.OrgInletService;
import com.eascs.workflow.sys.service.UserService;
import com.eascs.workflow.sys.vo.EmployeeVo;
import com.eascs.workflow.sys.vo.UserVo;
import com.eascs.workflow.util.BankRowWriteHandler;
import com.eascs.workflow.wf.service.WFQueryService;
import com.eascs.workflow.wf.vo.SignTypeExportVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Controller
public class UserViewController extends BaseMasterViewController {

	protected final      Logger logger    = LoggerFactory.getLogger(getClass());
	private static final int    PAGE_SIZE = 100;
	@Autowired
	private UserService     userService;
	@Autowired
	private WFQueryService  wFQueryService;
	@Autowired
	private OrgInletService orgInletService;
	@Autowired
	private SysOrgDao       sysOrgDao;
	@Autowired
	private SysUserDao      userDao;

	@RequestMapping("/interface/test")
	public String interfaceTest() {
		sysOrgDao.getOrgListByLevel("16", ActOrgEntity.ORG_LEVEL_PROVINCE_FIN_COM);
		return null;
	}

	@RequestMapping("/list/user")
	public String getAllUser(EmployeeVo vo, @RequestParam(defaultValue = "0") Integer pageIndex) {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "USER_DIMISSION_MGR");
		StringBuffer pageUrl = new StringBuffer("/list/user?1=1");
		ViewContext.put("pageUrl", pageUrl);

		PageResult<Object[]> pageResult = userDao.getAllUser(vo, pageIndex);
		ViewContext.put("pageIndex", pageIndex);

		String[] titles = {"用户编号", "用户名", "入职状态", "入职时间","区域","岗位"};

		//Button detail = ButtonHelper.createAjaxButton("详情", "/customer/shop/rest/detailPage?customerShopId=", "USER_DIMISSION_UPDATE");
		Button update = ButtonHelper.createAjaxButton("修改", "/rest/user/detail?userNo=");
		//update.setPermissionCode("dczllrUpdateButton");
		Button[] detailButton = new Button[]{update};

		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles, pageUrl + "&pageIndex=");
		paginationInfo.setBuildPagingNavigation(true);
		paginationInfo.setMoreButtons(detailButton);
		//paginationInfo.setBuildRowNumber(true);
		paginationInfo.setFirstRenderColumnIndex(0);
		ViewContext.put("paginationInfo", paginationInfo);
		ViewContext.put("vo", vo);
		return "/user/all_user_list";
	}

	@RequestMapping("/search/user")
	public String getUserInfo(String userNo, String orgId, String pageIndex) {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "USER_SEARCH");
		StringBuffer pageUrl = new StringBuffer("/search/user?1=1");
		ViewContext.put("pageUrl", pageUrl);
		if (StringUtil.hasText(userNo)) {
			pageUrl.append("&userNo=").append(userNo);
		}
		if (StringUtil.hasText(orgId)) {
			pageUrl.append("&orgId=").append(orgId);
		}
		if (StringUtils.isBlank(pageIndex)) {
			pageIndex = "0";
		}

		if (StringUtils.isBlank(userNo) && StringUtils.isBlank(orgId)) {
			ViewContext.put("page", new PageResult<UserVo>());
			return "/user/list";
		}
		PageResult<UserVo> page = userService.getUserVo(userNo, orgId, 0, PAGE_SIZE);
		ViewContext.put("page", page);
		ViewContext.put("orgId", orgId);
		ViewContext.put("pageIndex", pageIndex);
		return "/user/list";
	}

	@RequestMapping("/download")
	public void downloadPlatform(UserVo uv, HttpServletResponse httpServletResponse, HttpServletRequest request,
	                             String pageIndex) {
		String             orgId     = "1";
		String             userNo    = null;
		PageResult<UserVo> page      = userService.getUserVo(userNo, "1", 0, 1000);
		int                pageTotal = page.getPageTotal();
		List<Object[]>     user      = new ArrayList<Object[]>();
		for (int pageNo = 0; pageNo < pageTotal; pageNo++) {
			page = userService.getUserVo(userNo, "1", pageNo, 1000);
			for (int i = 0; i <= page.getReturnDataSize() - 1; i++) {
				Object[] obj = new Object[4];
				obj[0] = page.getData().get(i).getUserNo();
				obj[1] = page.getData().get(i).getUserName();
				obj[2] = page.getData().get(i).getOrgNames();
				obj[3] = page.getData().get(i).getRoleNames();
				user.add(obj);
			}
		}

		saveReportStatByPlatform(user, orgId);
		String       path    = UserViewController.class.getResource("/excelTemplate").getPath();
		StringBuffer s       = new StringBuffer();
		String       outPath = s.append(path).append("/reportstat.xls").toString();
		OutputStream os      = null;
		try {
			String outfile;

			outfile = "所有人员名单及信息" + ".xls";

			String userAgent = request.getHeader("User-Agent");
			byte[] bytes     = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			File f = new File(outPath);
			if (!f.exists())
				throw new RuntimeIOException("file not found");
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			IoUtil.fileToOutputStream(f, byteArrayOutputStream);
			os.write(byteArrayOutputStream.toByteArray());
			os.flush();
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}

	}

	private List<Object[]> convertSignTypeListToObjcetArr(List<SignTypeExportVo> signTypeList) {
		List<Object[]> signTypeObjList = new ArrayList<Object[]>();
		for (SignTypeExportVo vo : signTypeList) {
			Object[] obj = new Object[16];
			obj[0] = vo.getLoanNo();
			obj[1] = vo.getNodeName();
			obj[2] = vo.getCreditManager();
			obj[3] = vo.getUnitName();
			obj[4] = vo.getProvinceName();
			obj[5] = vo.getIsSign();
			obj[6] = vo.getBcnszl();
			obj[7] = vo.getBctcwd();
			obj[8] = vo.getBchtzl();
			obj[9] = vo.getSpzp();
			obj[10] = vo.getSf();
			obj[11] = vo.getSptjls();
			obj[12] = vo.getFyj();
			obj[13] = vo.getBcsmqk();
			obj[14] = vo.getDh();
			obj[15] = vo.getQt();
			signTypeObjList.add(obj);
		}
		return signTypeObjList;
	}

	@RequestMapping("/signtype/view")
	public String signtypeView() {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "SBJQYJDC");
		User                            user        = UserHolder.getUser();
		ModelResult<List<ActOrgEntity>> modelResult = orgInletService.getProvinceWithUser(user.getNo());
		ViewContext.put("provinceList", modelResult.getModel());
		return "/user/signtype-export";
	}

	@RequestMapping("/signtype/export")
	public void signtypeExport(HttpServletResponse httpServletResponse, HttpServletRequest request, String province,
	                           String startTime, String endTime) {
		OutputStream os = null;
		try {
			List<SignTypeExportVo> signTypeList    = wFQueryService.getYHSBSCNodeSignType(province, startTime, endTime);
			List<Object[]>         signTypeObjList = convertSignTypeListToObjcetArr(signTypeList);
			String                 filePath        = saveSignTypeReport(signTypeObjList);
			String                 outfile         = "signtype" + ".xls";
			String                 userAgent       = request.getHeader("User-Agent");
			byte[]                 bytes           = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			File f = new File(filePath);
			if (!f.exists())
				throw new RuntimeIOException("file not found");
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			IoUtil.fileToOutputStream(f, byteArrayOutputStream);
			os.write(byteArrayOutputStream.toByteArray());
			os.flush();
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
	}

	public String saveSignTypeReport(List<Object[]> data) {
		// 模板
		String soucreFileName = "/excelTemplate/signtype-exp-template.xls";
		// 输出路径
		String       path    = UserViewController.class.getResource("/excelTemplate").getPath();
		StringBuffer s       = new StringBuffer();
		String       outPath = s.append(path).append("/signtype-export.xls").toString();
		// 包含的列
		int col = 16;
		// 需要统计的列
		int[]  arr   = {};
		String title = "";
		// 开始的表格，行，列
		int sheetIndex  = 0;
		int rowIndex    = 2;
		int columnIndex = 0;
		BankRowWriteHandler bankRowWriteHandler = new BankRowWriteHandler(data, col, arr, Arrays.asList(title),
				sheetIndex, rowIndex, columnIndex);
		// 生产excel
		write(soucreFileName, outPath, bankRowWriteHandler);
		return outPath;
	}

	public String saveReportStatByPlatform(List<Object[]> data, String orgId) {

		// 模板
		String soucreFileName = "/excelTemplate/excel-member.xls";
		// 输出路径
		String       path    = UserViewController.class.getResource("/excelTemplate").getPath();
		StringBuffer s       = new StringBuffer();
		String       outPath = s.append(path).append("/reportstat.xls").toString();

		// 包含的列
		int col = 4;
		// 需要统计的列
		int[]  arr   = {};
		String title = "";
		// 开始的表格，行，列
		int sheetIndex  = 0;
		int rowIndex    = 2;
		int columnIndex = 0;
		BankRowWriteHandler bankRowWriteHandler = new BankRowWriteHandler(data, col, arr, Arrays.asList(title),
				sheetIndex, rowIndex, columnIndex);
		// 生产excel
		write(soucreFileName, outPath, bankRowWriteHandler);
		return path + "/" + outPath;
	}

	public void write(String soucreFileName, String outPath, BankRowWriteHandler bankRowWriteHandler) {
		IoUtil.createDirectorieIfMissing(new File(outPath).getParentFile());
		try {
			ExcelApiHelper.writeHandle(new FileOutputStream(outPath),
					UserViewController.class.getResourceAsStream(soucreFileName), bankRowWriteHandler);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ControllerException(e);
		}
	}
}
